package gen.core;

import gen.core.models.Column;
import gen.core.models.Cell;
import gen.core.models.Row;
import gen.core.models.Table;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TableFactory {
	private static TableFactory factory = null;

	private TableFactory() {
	}

	public synchronized static TableFactory getInstance() {
		if (factory == null) {
			factory = new TableFactory();
		}

		return factory;
	}

	public Table newTable(ResultSet rs) throws SQLException {
		Table aTable = new Table();
		List<Row> aRowList = new ArrayList<Row>();
		ResultSetMetaData meta = rs.getMetaData();

		// 分析表结构，得到列信息
		int cols = meta.getColumnCount();
		Column[] columns = new Column[cols];
		for (int i = 0; i < cols; i++) {
			String aColumnName = meta.getColumnName(i + 1);
			columns[i] = new Column();
			columns[i].setName(aColumnName);
			columns[i].setType(meta.getColumnType(i + 1));
		}
		aTable.setColumns(columns);

		// 读取表数据，得到行信息
		for (; rs.next();) {
			Row aRow = new Row();
			Cell[] cells = new Cell[cols];

			for (int i = 0; i < cols; i++) {
				cells[i] = new Cell();
				cells[i].setData(rs.getObject(i + 1));
				cells[i].setIndex(i);
			}

			aRow.setCells(cells);
			aRowList.add(aRow);
		}
		aTable.setRows(aRowList.toArray(new Row[0]));

		return aTable;
	}

}
